<template>
  <div class="page-cont">
    <van-nav-bar
      title="日计划管理"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <div class="list">
      <vue-mob-cal
        v-model="currentDate"
        :mode.sync="mode"
      >
        <template #right>
          <span
            class="today"
            @click="currentDate = new Date()"
          >今日</span>
        </template>
        <template #title>
          <div class="date-tit">
            <div
              class="l"
              @click="prevMonth"
            >
              <van-icon name="arrow-left" />
            </div>
            {{ currentDate.getFullYear() }} / {{ currentDate.getMonth() + 1 }}
            <div
              class="r"
              @click="nextMonth"
            >
              <van-icon name="arrow" />
            </div>
          </div>
        </template>
        <template #day="props">
          <span v-if="props.util.isToday(props.date)">今</span>
          <span v-else>{{ props.date.getDate() }}</span>
          <!-- A dot will appear at the bottom -->
          <span
            v-if="planDaysExist.indexOf(dayjs(props.date).format('YYYY-MM-DD')) !== -1"
            class="mindot"
          />
          <span class="dot" />
        </template>
      </vue-mob-cal>
      <div class="current-date">
        <span>{{ dayjs(currentDate).format("YYYY-MM-DD") }}生产计划</span>
        <van-icon
          v-if="!noEditable"
          @click="showPreBridge"
          name="add-o"
        />
      </div>
      <transition name="van-slide-right">
        <div
          v-if="preBridgeShow"
          class="pre-bridge-list"
        >
          <van-nav-bar
            title="梁片信息"
            left-arrow
            @click-left="$router.go(-1)"
          />
          <div class="tree">
            <pre-bridge-tree
              :date="currentDate"
              :plans="currentPlanList"
              @addTask="addTask"
            />
          </div>
        </div>
      </transition>

      <dayplan-item
        v-for="plan in currentPlanList"
        :key="plan.id"
        :plan="plan"
        :no-editable="noEditable"
        @cancel="cancelPlan"
        @remove="removeTask"
        @submit="submitTask"
      />
      <van-empty
        v-if="!currentPlanList.length"
        description="暂无数据"
      />
    </div>
  </div>
</template>

<script>
import dayjs from "dayjs";
import DayplanItem from "./components/DayplanItem.vue";
import PreBridgeTree from "./components/PreBridgeTree/index.vue";
export default {
  name: "DayPlanPage",
  components: {
    DayplanItem,
    PreBridgeTree
  },
  data() {
    return {
      dayjs,
      type: '',
      originState: null,
      mode: "month",
      currentDate: new Date(),
      planList: [],
      preBridgeShow: false
    };
  },
  computed: {
    noEditable() {
      return this.type === 'steel'
    },
    currentDateStr() {
      return dayjs(this.currentDate).format("YYYYMMDD");
    },
    currentPlanList() {
      return this.planList.filter(item => {
        return item.addTime === this.currentDateStr;
      });
    },
    planDaysExist() {
      let list = []
      this.planList.forEach(item => {
        list.push(this.$options.filters.timeDate(item.addTime, "YYYY-MM-DD"))
      })
      return list
    }
  },
  watch: {
    currentDate(newV, oldV) {
      let newYearMonth = dayjs(newV).format("YYYY-MM");
      let oldYearMonth = dayjs(oldV).format("YYYY-MM");
      if (newYearMonth !== oldYearMonth) {
        this.getMonthPlan();
      }
    }
  },
  created() {
    this.originState = history.state.current; // 存储原始的状态
    this.type = this.$route.query.type || ''
    this.getMonthPlan();
    window.addEventListener("popstate", this.onPopstate, false);
  },
  beforeDestroy() {
    window.removeEventListener("popstate", this.onPopstate, false);
  },
  methods: {
    prevMonth() {
      this.currentDate = new Date(
        this.currentDate.getFullYear(),
        this.currentDate.getMonth() - 1,
        1
      );
    },
    nextMonth() {
      this.currentDate = new Date(
        this.currentDate.getFullYear(),
        this.currentDate.getMonth() + 1,
        1
      );
    },
    async getMonthPlan() {
      // GET_DAY_PLAN_TIME_LIST
      let time = dayjs(this.currentDate).format("YYYYMM"); 
      this.$toast.loading({  message: '正在登陆...', forbidClick: true });
      let list = await this.api.GET_DAY_PLAN_TIME_LIST({ time })
      this.$toast.clear()

      this.$set(this, 'planList', list)
    },
    addTask(item) {
      console.log(item)
      this.getMonthPlan();
    },
    onPopstate(e) {
      if (e.state && (e.state.current === this.originState || e.state.target === this.originState)) {
        this.preBridgeShow = false
      }
    },
    // 显示预制梁弹窗
    showPreBridge() {
      this.preBridgeShow = true
      // 添加URL记录
      window.history.pushState({target: this.originState, random: Math.random()}, "", location.href);
    },
    // 取消计划
    async cancelPlan(plan) {
      this.$toast.loading({  message: '加载中...', forbidClick: true });
      await this.api.UPDATE_DAY_PLAN({ id: plan.id, delFlag: true })
      this.$toast.clear()
      this.getMonthPlan();
    },
    // 下达&调整任务
    async submitTask(plan) {
      if (parseInt(plan.addTask) !== 1) {
        this.$toast.loading({  message: '加载中...', forbidClick: true });
        await this.api.START_DAY_PLAN({id: plan.id, time: dayjs().format('YYYYMMDDHHmmss')})
        this.$toast.clear()
        this.getMonthPlan();
      } else {
        this.$router.push({
          path: '/dayplan/set',
          query: {json: JSON.stringify(plan)}
        })
      }
    },
    // 删除任务
    async removeTask(plan) {
      this.$toast.loading({  message: '加载中...', forbidClick: true });
      let res = await this.api.GET_DAY_PLAN_TASK({
        searchName: 'dayPlanId',
        searchKeyword: plan.id,
        pageNo: 1, pageSize: 100000
      })
      const list = res.list.map(item => this.api.DEL_DAY_PLAN_TASK(item.id))
      await Promise.all(list)
      this.$toast.clear()
    }
  },
};
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
